﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Barbar.Colonization.Model;

namespace Barbar.Colonization.WorldEditor {
  public delegate void OnTileClick(Tile tile);

  public partial class WorldRenderer : UserControl {
    private World m_World;
    private Point m_LeftTopGrid = new Point(0, 0);
    private Size m_Size;
    private const int TileWidth = 32;
    private const int TileHeight = 32;
    public event OnTileClick TileClick;

    private void RecalculateSize() {
      m_Size = new Size(Size.Width / TileWidth + 1, Size.Height / TileHeight + 1);
    }

    public WorldRenderer() {
      InitializeComponent();
      RecalculateSize();
    }

    protected override void OnResize(EventArgs e) {
      RecalculateSize();
    }

    protected override void OnPaint(PaintEventArgs e) {
      if (m_World != null) {
        for (int x = m_LeftTopGrid.X; x <= m_LeftTopGrid.X + m_Size.Width && x < m_World.Width; x++)
          for (int y = m_LeftTopGrid.Y; y <= m_LeftTopGrid.Y + m_Size.Height && y < m_World.Height; y++) {
            ITileType tileType = m_World[x, y].TileType;
            e.Graphics.DrawImage(tileType.Images.MergedImage, (x - m_LeftTopGrid.X) * TileWidth, (y - m_LeftTopGrid.Y) * TileHeight, TileWidth, TileHeight);
          }
      }
    }

    public void SetWorld(World world) {
      vScrollBar.Minimum = 0;
      vScrollBar.Maximum = world.Height - 1;

      hScrollBar.Minimum = 0;
      hScrollBar.Maximum = world.Width - 1;

      m_World = world;
    }

    private void WorldRendered_OnMouseClick(object sender, MouseEventArgs e) {
      int x = e.X / TileWidth + m_LeftTopGrid.X;
      int y = e.Y / TileHeight + m_LeftTopGrid.Y;

      if (x >= 0 && x < m_World.Width && y >= 0 && y < m_World.Height && TileClick != null)
        TileClick(m_World[x, y]);
    }

    private void vScrollBar_OnScroll(object sender, ScrollEventArgs e) {
      m_LeftTopGrid.Y = e.NewValue;
      Refresh();
    }

    private void hScrollBar_OnScroll(object sender, ScrollEventArgs e) {
      m_LeftTopGrid.X = e.NewValue;
      Refresh();
    }
  }
}
